import React, { useState, Fragment, useEffect } from 'react';
import { Table, Input, Button, Row, Col, Tooltip, Divider, message, Typography } from 'antd';
import { withRouter, router } from 'umi';
import Pagination from '@/components/Pagination';
import { useRequest, defaultFormatResult } from '@/hooks';
import { ENTRY_STATUS_MAP, sortStringToNumber } from '@/pages/EntryManage/utils';
import { toArray } from '@/utils/utils';
import moment from 'moment';
import useDictionary from '@/hooks/useDictionary';
import { size, get } from 'lodash';
import authHelper from '@/utils/auth/helper';
import IconFont from '@/components/IconFont';
import { eventTrack } from '@/utils/track';
import Icon from '@/components/IconPro';
import MoreOperateModal from '../components/MoreOperateModal';
import styles from './index.less';
import { queryCandidateProcessList, getOrganizationWithFullName } from '../services';

const { Paragraph } = Typography;
const { checkCode } = authHelper;

// 入职管理-待入职
const WaitEntryList = ({ location }) => {
    const [modalVisible, setModalVisible] = useState(false);
    const [modalEntryPersonnelCode, setModalEntryPersonnelCode] = useState();
    const [modalEntryOperateType, setModalEntryOperateType] = useState(1);
    const [sexTypeList, getSexTypeText] = useDictionary('sexType');
    const user = JSON.parse(localStorage.getItem('user') || '{}');
    const { employeeCode } = user;

    const { query = {} } = location;
    const { pageNo = 1, pageSize = 10, changeDateCode } = query;

    useEffect(() => {
        if (changeDateCode) {
            setModalVisible(true);
            setModalEntryOperateType(2);
            setModalEntryPersonnelCode(changeDateCode);
        }
    }, [changeDateCode]);

    const [searchText, setSearchText] = useState(query?.entryPersonnelName);

    // 请求数据
    const { data, loading, refresh } = useRequest(
        () =>
            queryCandidateProcessList({
                pageNo,
                pageSize,
                ...query,
                order: sortStringToNumber(query?.order)
            }),
        {
            ready: !!query,
            refreshDeps: [query],
            ...defaultFormatResult
        }
    );
    const tableDataSource = data?.rows;
    const total = data?.total;

    // 获取面包屑机构路径
    const { run: runFullname, fetches: fullnameFetches } = useRequest(params => getOrganizationWithFullName(params), {
        manual: true,
        fetchKey: organizationCode => organizationCode,
        ...defaultFormatResult
    });

    // 替换url
    const handleReplacePage = param => {
        history.push({ query: { ...query, ...param } });
    };

    // 分页切换
    const handlePaginationChange = pagination => {
        handleReplacePage({ pageNo: pagination?.current, pageSize: pagination?.pageSize });
    };

    // 渲染状态按钮
    const renderStatusButton = record => {
        const {
            entryStatus,
            recruitDirectorCode,
            assignEmployeeList = [],
            step,
            entryPersonnelCode,
            organizationCode,
            contractOrganizationCode
        } = record;
        let isShowBtn = false;

        if (size(assignEmployeeList?.filter(item => item?.employeeCode === employeeCode)) > 0) {
            // 登录人在处理列表里面
            isShowBtn = true;
        } else if (employeeCode === recruitDirectorCode) {
            // 登录人是招聘负责人，但是不在处理列表里面，状态为1的时候需要按钮
            if (entryStatus === 1) {
                isShowBtn = true;
            }
        }

        if (isShowBtn === true && checkCode(ENTRY_STATUS_MAP[entryStatus].code)) {
            return (
                <>
                    <Tooltip
                        title={`${ENTRY_STATUS_MAP[entryStatus]?.tipText || ENTRY_STATUS_MAP[entryStatus]?.name}${
                            step < 2 ? '，待完成入职引导后才能接收' : ''
                        }`}
                    >
                        <IconFont
                            icon={ENTRY_STATUS_MAP[entryStatus]?.icon}
                            disabled={step < 2} // 待入职员工需要填写数据才能接收
                            className={styles.iconButton}
                            onClick={async () => {
                                await eventTrack({
                                    eventName:
                                        'personnel_management_onboard_and_leave_entry_manage_wait_entry_operator_click',
                                    pageName: 'personnel_management_onboard_and_leave',
                                    eventProps: {
                                        click_context: `${record.employeeName}-${ENTRY_STATUS_MAP[entryStatus]
                                            ?.tipText || ENTRY_STATUS_MAP[entryStatus]?.name}`
                                    }
                                });
                                const pathname = ENTRY_STATUS_MAP[entryStatus]?.url;
                                const param = { entryPersonnelCode, organizationCode, contractOrganizationCode };
                                if (pathname) {
                                    history.push({
                                        pathname,
                                        query: param
                                    });
                                }
                            }}
                        />
                    </Tooltip>
                    {employeeCode === recruitDirectorCode && <Divider type="vertical" />}
                </>
            );
        }
        return null;
    };

    const columns = [
        {
            title: '姓名',
            dataIndex: 'employeeName',
            key: 'employeeName',
            width: 180,
            render: (text, record) => (
                <>
                    {checkCode('office:personnel:progress:entry:detail') ? (
                        <Button
                            type="link"
                            alt={text}
                            className={styles.link}
                            onClick={async () => {
                                await eventTrack({
                                    eventName:
                                        'personnel_management_onboard_and_leave_entry_manage_wait_entry_name_click',
                                    pageName: 'personnel_management_onboard_and_leave',
                                    eventProps: {
                                        click_context: text
                                    }
                                });
                                history.push({
                                    pathname:
                                        '/office/personnelManagement/onboardAndLeave/entryManage/entryEmployeeDetail',
                                    query: {
                                        entryPersonnelCode: record?.entryPersonnelCode
                                        // organizationCode: record?.organizationCode
                                    }
                                });
                            }}
                        >
                            {text}
                        </Button>
                    ) : (
                        text
                    )}
                </>
            )
        },
        {
            title: '性别',
            dataIndex: 'sex',
            key: 'sex',
            width: 150,
            filteredValue: toArray(query?.sex),
            filterMultiple: false,
            filters: sexTypeList,
            render: text => getSexTypeText(text)
        },
        {
            title: '组织机构',
            dataIndex: 'organizationName',
            key: 'organizationName',
            render: (text, record) => {
                const { organizationCode } = record;
                return (
                    <div
                        onMouseEnter={() => {
                            if (!fullnameFetches[organizationCode]) {
                                runFullname([organizationCode]);
                            }
                        }}
                    >
                        <Tooltip
                            title={
                                get(fullnameFetches[organizationCode], 'data[0].fullOrganizationName') || (
                                    <Icon type="loading" />
                                )
                            }
                        >
                            <Paragraph ellipsis className={styles.listParagraph}>
                                {text}
                            </Paragraph>
                        </Tooltip>
                    </div>
                );
            }
        },
        {
            title: '岗位',
            dataIndex: 'dutyName',
            key: 'dutyName',
            width: 280,
            render: (text, record) => (
                <>
                    <Row type="flex">
                        <Col>
                            <Tooltip title={text}>
                                <Paragraph ellipsis className={styles.listParagraph}>
                                    {text || '-'}
                                </Paragraph>
                            </Tooltip>
                        </Col>
                        <Col>{record?.rankValue ? `/${record.rankValue}` : '-'}</Col>
                    </Row>
                </>
            )
        },
        {
            title: '入职日期',
            dataIndex: 'entryDate',
            key: 'entryDate',
            sorter: true,
            sortOrder: query?.order,
            width: 150,
            render: text => moment(text).format('YYYY-MM-DD')
        },
        {
            title: '招聘负责人',
            dataIndex: 'recruitDirectorName',
            key: 'recruitDirectorName',
            render: text => text
        },
        {
            title: '状态',
            dataIndex: 'entryStatus',
            key: 'entryStatus',
            width: 150,
            render: (text, record) => (
                <>
                    {ENTRY_STATUS_MAP[text]?.name}
                    {size(record.backReason) > 0 && (
                        <Tooltip title={`退回原因：${record?.backReason}`}>
                            <IconFont
                                isButton
                                style={{ marginLeft: 3, color: '#ffa22d' }}
                                icon="rollback"
                                onClick={() => {
                                    history.push({
                                        pathname:
                                            '/office/personnelManagement/onboardAndLeave/entryManage/entryEmployeeDetail',
                                        query: {
                                            tab: 'record',
                                            entryPersonnelCode: record?.entryPersonnelCode
                                        },
                                        state: { tabRoute: true, tabRefresh: true }
                                    });
                                }}
                            />
                        </Tooltip>
                    )}
                </>
            )
        },
        {
            title: '处理人',
            dataIndex: 'assignEmployeeList',
            key: 'assignEmployeeList',
            render: text => text?.map(item => item.employeeName).join('、')
        },
        {
            title: '操作',
            dataIndex: 'operation',
            key: 'operation',
            align: 'left',
            fixed: 'right',
            width: 216,
            render: (text, record) => {
                const {
                    entryStatus,
                    isSignedContract,
                    recruitDirectorCode,
                    assignEmployeeList,
                    modifyHandlerButtonVisible
                } = record;
                const isShowModifyHandlerBtn = modifyHandlerButtonVisible;
                //  || checkCode('office:personnel:progress:entry:modifyHandler');

                return (
                    <>
                        {renderStatusButton(record)}

                        {isShowModifyHandlerBtn && (
                            <Tooltip title={size(assignEmployeeList) > 1 ? '多个处理人不能指派' : '修改处理人'}>
                                <IconFont
                                    disabled={size(assignEmployeeList) > 1} // 多个处理人不能指派
                                    icon="iconzhidingfuzeren1"
                                    className={styles.iconButton}
                                    onClick={() => {
                                        setModalEntryOperateType(1);
                                        setModalEntryPersonnelCode(record?.entryPersonnelCode);
                                        setModalVisible(true);
                                    }}
                                />
                            </Tooltip>
                        )}
                        {employeeCode === recruitDirectorCode && (
                            <>
                                {isShowModifyHandlerBtn && <Divider type="vertical" />}
                                <Tooltip
                                    title={record?.applyEntryDateStatus === 'waitfor' ? '确认入职时间' : '修改入职时间'}
                                >
                                    <IconFont
                                        disabled={entryStatus > 5 || isSignedContract === 1} // 之前逻辑是办理入职完或签订劳动合同不允许在修改入职时间
                                        icon="iconxiugairuzhishijian"
                                        className={styles.iconButton}
                                        onClick={() => {
                                            setModalEntryOperateType(2);
                                            setModalEntryPersonnelCode(record?.entryPersonnelCode);
                                            setModalVisible(true);
                                        }}
                                    />
                                </Tooltip>
                                <Divider type="vertical" />
                                <Tooltip title="终止入职">
                                    <IconFont
                                        disabled={entryStatus > 5 || isSignedContract === 1} // 之前逻辑是非招聘负责人、办理入职完或签订劳动合同不允许终止入职
                                        icon="iconzhongzhiruzhi1"
                                        className={styles.iconButton}
                                        onClick={() => {
                                            setModalEntryOperateType(3);
                                            setModalEntryPersonnelCode(record?.entryPersonnelCode);
                                            setModalVisible(true);
                                        }}
                                    />
                                </Tooltip>
                            </>
                        )}
                    </>
                );
            }
        }
    ];

    // 表格筛选、排序等操作
    const handleTableChange = (_, filters = {}, sorter) => {
        const { sex } = filters;
        const { order } = sorter;

        handleReplacePage({
            pageNo: 1,
            sex: sex[0],
            order
        });
    };

    return (
        <Fragment>
            {/* 搜索 */}
            <div className={styles.searchWrap}>
                <Row type="flex" gutter={16}>
                    <Col>
                        <Input
                            placeholder="搜索姓名"
                            value={searchText}
                            onPressEnter={() => {
                                handleReplacePage({ pageNo: 1, entryPersonnelName: searchText });
                            }}
                            onChange={e => {
                                setSearchText(e.target.value);
                            }}
                            onFocus={() => {
                                eventTrack({
                                    eventName:
                                        'personnel_management_onboard_and_leave_entry_manage_wait_entry_name_input_click',
                                    pageName: 'personnel_management_onboard_and_leave'
                                });
                            }}
                            allowClear
                        />
                    </Col>
                    <Col>
                        <Button
                            type="primary"
                            onClick={() => {
                                eventTrack({
                                    eventName:
                                        'personnel_management_onboard_and_leave_entry_manage_wait_entry_search_submit_click',
                                    pageName: 'personnel_management_onboard_and_leave',
                                    eventProps: {
                                        click_context: `姓名：${searchText}`
                                    }
                                });
                                handleReplacePage({ pageNo: 1, entryPersonnelName: searchText });
                            }}
                        >
                            搜索
                        </Button>
                    </Col>
                </Row>
            </div>
            <Table
                loading={loading}
                rowKey="id"
                columns={columns}
                dataSource={tableDataSource}
                pagination={false}
                onChange={handleTableChange}
                scroll={{ x: 'max-content' }}
                style={{
                    tableLayout: 'fixed',
                    wordBreak: 'break-word'
                }}
            />
            {/* 分页 */}
            <Pagination
                current={query?.pageNo}
                pageSize={query?.pageSize}
                loading={loading}
                total={total}
                onChange={handlePaginationChange}
            />

            {modalEntryPersonnelCode && (
                <MoreOperateModal
                    entryPersonnelCode={modalEntryPersonnelCode}
                    operateType={modalEntryOperateType}
                    changeDateCode={changeDateCode}
                    setModalEntryOperateType={setModalEntryOperateType}
                    visible={modalVisible}
                    maskClosable={false}
                    title={changeDateCode && '确认入职时间'}
                    okButtonProps={{ style: { marginLeft: 12 } }}
                    onCancel={() => {
                        setModalEntryOperateType();
                        setModalEntryPersonnelCode(null);
                        setModalVisible(false);
                        if (changeDateCode) {
                            history.replace('/office/personnelManagement/onboardAndLeave/entryManage/waitEntry');
                        }
                    }}
                    onOk={({ code, msg }) => {
                        if (code === 10000) {
                            message.success(msg);
                            setModalEntryOperateType();
                            setModalEntryPersonnelCode(false);
                            refresh();
                            if (changeDateCode) {
                                history.replace('/office/personnelManagement/onboardAndLeave/entryManage/waitEntry');
                            }
                        } else {
                            message.error(msg);
                        }
                    }}
                />
            )}
        </Fragment>
    );
};

export default withRouter(WaitEntryList);
